#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
generate_html_index.py

功能：扫描指定目录下的所有 .html 文件，按目录结构生成带层级的导航首页 index.html
"""

import os
from pathlib import Path
import re
import argparse

# 提取 title 的正则
TITLE_REGEX = re.compile(r'<title[^>]*>(.*?)</title>', re.IGNORECASE | re.DOTALL)


def extract_title(file_path):
    """从 HTML 文件提取标题，为空则返回文件名（不含扩展名）"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read(4096)
        match = TITLE_REGEX.search(content)
        if match:
            title = match.group(1).strip()
            title = re.sub(r'<[^>]+>', '', title)  # 清理标签
            title = title.strip()
            if title:
                return title
    except Exception as e:
        print(f"⚠️  无法读取 {file_path}: {e}")
    return Path(file_path).stem  # fallback


def build_file_tree(root_dir, html_files):
    """
    构建目录树结构
    返回嵌套字典：{'dir': {'file.html': 'Title', 'subdir': { ... }}}
    """
    tree = {}

    for file_path in html_files:
        # 获取相对于 root_dir 的路径部分
        try:
            rel_path = file_path.relative_to(root_dir)
        except ValueError:
            rel_path = file_path.name  # 安全 fallback

        parts = rel_path.parts
        current = tree
        # 遍历路径的每一级（除了最后一级是文件）
        for part in parts[:-1]:
            if part not in current:
                current[part] = {}
            current = current[part]
        # 最后一级是文件
        title = extract_title(file_path)
        current[parts[-1]] = title

    return tree


def generate_nav_html(tree, base_url="", indent=""):
    """
    递归生成 HTML 导航列表
    """
    html = ""
    for name, content in tree.items():
        if isinstance(content, dict):
            # 是目录
            dir_name = name
            html += f'{indent}  <li class="dir"><strong>📁 {dir_name}</strong>\n{indent}    <ul>\n'
            html += generate_nav_html(content, base_url, indent + "      ")
            html += f'{indent}    </ul>\n{indent}  </li>\n'
        else:
            # 是文件
            title = content
            href = base_url + str(Path(name)).replace("\\", "/")  # 确保路径分隔符正确
            html += f'{indent}  <li><a href="{href}">{title}</a></li>\n'
    return html


def generate_index_html(root_dir, output_path, base_url=""):
    """
    主函数：扫描目录，生成 index.html
    """
    root_dir = Path(root_dir).resolve()
    output_path = Path(output_path).resolve()

    if not root_dir.is_dir():
        print(f"❌ 目录不存在: {root_dir}")
        return

    # 收集所有 .html 文件
    html_files = []
    for file_path in root_dir.rglob("*.html"):  # 递归扫描
        if file_path.is_file():
            html_files.append(file_path)

    if not html_files:
        print(f"⚠️  在 {root_dir} 中未找到任何 .html 文件")
        return

    print(f"🔍 找到 {len(html_files)} 个 HTML 文件，正在构建目录结构...")

    # 构建树形结构
    tree = build_file_tree(root_dir, html_files)

    # 生成导航 HTML
    nav_html = generate_nav_html(tree, base_url)

    # 获取项目名称（根目录名）
    project_name = root_dir.name or "文档导航"

    # 完整 HTML 页面
    index_content = f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{project_name}</title>
  <meta name="generator" content="generate_html_index.py">
  <style>
    body {{
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
      line-height: 1.7;
      color: #333;
      max-width: 900px;
      margin: 40px auto;
      padding: 20px;
      background: #f8f9fa;
    }}
    h1 {{
      text-align: center;
      color: #0056b3;
      border-bottom: 2px solid #007acc;
      padding-bottom: 10px;
      margin-bottom: 30px;
      font-size: 1.8em;
    }}
    ul {{
      list-style: none;
      padding-left: 20px;
    }}
    li {{ margin: 8px 0; }}
    .dir {{ margin: 16px 0; }}
    a {{
      text-decoration: none;
      color: #0056b3;
      font-size: 1.05em;
    }}
    a:hover {{
      color: #003d82;
      text-decoration: underline;
    }}
    footer {{
      text-align: center;
      margin-top: 50px;
      color: #777;
      font-size: 0.9em;
    }}
    @media (max-width: 600px) {{
      body {{ padding: 15px; }}
      h1 {{ font-size: 1.5em; }}
      ul {{ padding-left: 15px; }}
    }}
  </style>
</head>
<body>
  <h1>📚 {project_name}</h1>
  <ul>
{nav_html}  </ul>
  <footer>
    生成于 {__import__('datetime').datetime.now().strftime('%Y年%m月%d日 %H:%M')}
  </footer>
</body>
</html>'''

    # 写入文件
    try:
        output_path.parent.mkdir(parents=True, exist_ok=True)
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(index_content)
        print(f"✅ 成功生成导航页: {output_path}")
    except Exception as e:
        print(f"❌ 写入文件失败: {e}")


def main():
    parser = argparse.ArgumentParser(description="扫描目录下的 HTML 文件，按层级生成 index.html 导航页")
    parser.add_argument('--dir', type=str, default='.', help='要扫描的根目录 (默认: 当前目录)')
    parser.add_argument('--output', type=str, default='index.html', help='输出的 index.html 路径 (默认: index.html)')
    parser.add_argument('--base-url', type=str, default='', help='链接前缀，如: https://example.com/docs/')

    args = parser.parse_args()

    generate_index_html(args.dir, args.output, args.base_url)


if __name__ == '__main__':
    main()